package com.handpay.zztong.hp.withdraw.activity;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.adapter.WithDrawRecordsAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.widget.CalendarDialogView;
import com.handpay.zztong.hp.paymentbill.widget.CalendarView;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.withdraw.bean.QueryWithdrawRecordBean;
import com.handpay.zztong.hp.withdraw.model.QueryWithdrawRecordModel;

import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

/***
 * 提现记录查询（账账通）
 */
public class QueryWithdrawRecordsActivity extends ZZTongActivity implements CalendarView.OnItemClickListener {

    private boolean isDatePickerDialog4StartDate = false;
    private ZZTShowDialog<CalendarDialogView> mCalendarDialog;

    // 起始日期控件
    private TextView startDateShowTextView;
    // 结束日期控件
    private TextView endDateShowTextView;


    private QueryWithdrawRecordsActivity context;
    private final String PER_PAGE_RECORD_NUM = "5";
    /**
     * 查询提现申请记录
     */
    private ListView WithdrawRecordsListView;
    // 起始日期
    private Date startDate;
    // 结束日期
    private Date endDate;
    private LinearLayout footerView;
    // 页码信息
    private TextView tvPageInfo;
    // 分页按钮
    private Button btnLast, queryButton;
    private Button btnNext;
    private Button btnIndex;
    private Button btnEnd;
    private WithDrawRecordsAdapter queryWithDrawRecordsAdapter;
    private int pageNo = 1;
    // 总金额,总笔数
    private TextView tvWdAmounts, tvRwdAmounts, tvItems;
    private View wdHeadInfo;
    private int totalPages = 0;
    // 交易账单列表
    private List<QueryWithdrawRecordBean.WithdrawBody> bills;
    private QueryWithdrawRecordModel withdrawRecordModle = null;
    protected static final int UPDATE_VIEW_CODE = 0;
    protected static final int UPDATE_DATA_CODE = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_query_withdraw_records);
        super.onCreate(savedInstanceState);
        if (withdrawRecordModle == null) {
            withdrawRecordModle = new QueryWithdrawRecordModel();
        }
        initView();
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    public void initView() {
        context = this;
        mCalendarDialog = new ZZTShowDialog<CalendarDialogView>(this, new CalendarDialogView(this), R.style.dialog);
        mCalendarDialog.getContentView().getCalendar().setOnItemClickListener(this);

        WithdrawRecordsListView = (ListView) findViewById(R.id.queryBillsListView);

        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout headerView = (LinearLayout) inflater.inflate(R.layout.layout_query_withdraw_header, null);
        queryButton = (Button) headerView.findViewById(R.id.queryButton);
        queryButton.setOnClickListener(this);
        (headerView.findViewById(R.id.startDateRow)).setOnClickListener(this);
        (headerView.findViewById(R.id.endDateRow)).setOnClickListener(this);

        Date today = DateUtils.formatStringToDate(DateUtils.formatDateToString(new Date(), "yyyyMMdd"), "yyyyMMdd");
        startDateShowTextView = (TextView) headerView.findViewById(R.id.startDateShowTextView);
        endDateShowTextView = (TextView) headerView.findViewById(R.id.endDateShowTextView);
        startDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
        startDate = today;
        endDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
        endDate = new Date(today.getTime() + (24 * 60 * 60 * 1000) - 1);
        footerView = (LinearLayout) inflater.inflate(R.layout.layout_more_item, null);
        tvPageInfo = (TextView) footerView.findViewById(R.id.tvPageInfo);
        btnIndex = (Button) this.footerView.findViewById(R.id.btnIndex);
        btnEnd = (Button) this.footerView.findViewById(R.id.btnEnd);
        btnLast = (Button) this.footerView.findViewById(R.id.btnLast);
        btnNext = (Button) this.footerView.findViewById(R.id.btnNext);
        btnIndex.setOnClickListener(this);
        btnEnd.setOnClickListener(this);
        btnLast.setOnClickListener(this);
        btnNext.setOnClickListener(this);

        queryWithDrawRecordsAdapter = new WithDrawRecordsAdapter(this);
        WithdrawRecordsListView.addHeaderView(headerView);
        WithdrawRecordsListView.addFooterView(footerView);
        WithdrawRecordsListView.setAdapter(queryWithDrawRecordsAdapter);

        tvWdAmounts = (TextView) headerView.findViewById(R.id.tvWdAmounts);
        tvWdAmounts.setText("");
        tvRwdAmounts = (TextView) headerView.findViewById(R.id.tvRwdAmounts);
        tvRwdAmounts.setText("");
        wdHeadInfo = headerView.findViewById(R.id.wd_header_info);
        tvItems = (TextView) headerView.findViewById(R.id.tvItems);
        tvItems.setText("");
        // queryWithDrawRecords(startDate, endDate, pageNo,
        // PER_PAGE_RECORD_NUM);
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.withdraw_records_title), true);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.startDateRow) {
            this.isDatePickerDialog4StartDate = true;
            mCalendarDialog.getContentView().setCalendarData(startDate);
            mCalendarDialog.show();
        } else if (i == R.id.endDateRow) {
            this.isDatePickerDialog4StartDate = false;
            mCalendarDialog.getContentView().setCalendarData(endDate);
            mCalendarDialog.show();

        } else if (i == R.id.queryButton || i == R.id.btnIndex) {
            pageNo = 1;
            // 查询
            if (DateUtils.isOkDate(this, startDate, endDate) == true) {
                if (DateUtils.changequerystate(startDate, endDate)) {
                    // 查询
                    queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }

        } else if (i == R.id.btnNext) {
            pageNo++;
            if (DateUtils.isOkDate(this, startDate, endDate) == true) {
                if (DateUtils.changequerystate(startDate, endDate)) {
                    // 查询
                    queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
                } else {
                    this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        } else if (i == R.id.btnLast) {
            pageNo--;
            if (isDate() == true) {
                queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
            }

        } else if (i == R.id.btnEnd) {
            pageNo = totalPages;
            if (isDate() == true) {
                queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
            }

        }
    }

    private boolean isDate() {
        if (this.startDate == null) {
            showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
            return false;
        }
        if (this.endDate == null) {
            showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
            return false;
        }
        if (startDate.after(endDate)) {
            showAlertDialog(this, R.string.tip, R.string.select_date_tip);
            return false;
        }
        return true;
    }

    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // switch (which) {
    // case DialogInterface.BUTTON_POSITIVE:
    // // 编辑输入框，同样可以更新
    // datePicker.clearFocus();
    // Calendar calendar = Calendar.getInstance();
    // calendar.clear();
    // calendar.set(Calendar.YEAR, datePicker.getYear());
    // calendar.set(Calendar.MONTH, datePicker.getMonth());
    // calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
    // if (this.isDatePickerDialog) {
    // this.startDateShowTextView.setText(DateUtils.formatDateToString(calendar.getTime(),
    // "yyyy-MM-dd"));
    // this.startDate = calendar.getTime();
    // Log.i("result", "select---startDate=" + startDate.getTime());
    // Log.i("result", "select---endDate=" + endDate.getTime());
    // Log.i("result", "----------------------------------");
    // } else {
    // this.endDateTextView.setText(DateUtils.formatDateToString(calendar.getTime(),
    // "yyyy-MM-dd"));
    // this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 *
    // 1000) - 1);
    // Log.i("result", "select---startDate=" + startDate.getTime());
    // Log.i("result", "select---endDate=" + endDate.getTime());
    // Log.i("result", "----------------------------------");
    // }
    // break;
    // case DialogInterface.BUTTON_NEGATIVE:
    //
    // break;
    // default:
    // break;
    // }
    //
    // }

    public void queryWithDrawRecords(Date queryStartTime, Date queryEndTime, int pageNoString, String pageSizeString) {

        String account = AccountUtils.getAccountName(this);
        String channel = ClientEngine.CHANNEL;

        // 设置请求参数
        // queryRWDRecords.setStartTime(DateUtils.formatDateToString(queryStartTime,
        // "yyyyMMddHHmmss"));
        // queryRWDRecords.setEndTime(DateUtils.formatDateToString(queryEndTime,
        // "yyyyMMddHHmmss"));
        // queryRWDRecords.setaccount(SecureManager.getInstance().des(account,1,
        // null));
        // queryRWDRecords.setpageNo(pageNoString);
        // queryRWDRecords.setpageSize(pageSizeString);
        // queryRWDRecords.setchannel(channel);
        //
        // //开始发送请求
        // queryRWDRecords.doPost();
        Hashtable<String, String> hashtable = new Hashtable<String, String>(6);
        hashtable.put("startTime", DateUtils.formatDateToString(queryStartTime, "yyyyMMddHHmmss"));
        hashtable.put("endTime", DateUtils.formatDateToString(queryEndTime, "yyyyMMddHHmmss"));
        hashtable.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(account, 1, null));
        hashtable.put("pageNo", "" + pageNoString);
        hashtable.put("pageSize", pageSizeString);
        hashtable.put(BaseProtocolKey.CHANNEL, channel);
//		doPost(this, HttpUrlConstant.Do_NewQueryRWDRecords, hashtable);
        withdrawRecordModle.doQueryWithdrawRecord(this, hashtable, new BusinessEngineListener<QueryWithdrawRecordBean>() {
            @Override
            public void callbackBusinessResponse(QueryWithdrawRecordBean bean) {
                if (bean != null)
                    queryBillsSuccessHandler.obtainMessage(UPDATE_DATA_CODE, bean).sendToTarget();
            }
        });
    }

    // 成功获取数据handler
    private Handler queryBillsSuccessHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_VIEW_CODE:
                    // 通知adapter
                    queryWithDrawRecordsAdapter.notifyDataSetChanged();
                    break;
                case UPDATE_DATA_CODE:
                    QueryWithdrawRecordBean bean = (QueryWithdrawRecordBean) msg.obj;
                    totalPages = CommonUtils.objectToInt(bean.getTotalPages());
                    HPLog.d(HPLog.SSX_TAG, bean.toString());
                    if (bean.getList() == null || bean.getList().size() == 0) {
                        showAlertDialog(QueryWithdrawRecordsActivity.this, R.string.tip, R.string.no_wd_data);
                        queryWithDrawRecordsAdapter.clear();
                        footerView.setVisibility(View.GONE);
                        tvRwdAmounts.setVisibility(View.GONE);
                        tvWdAmounts.setVisibility(View.GONE);
                        footerView.setVisibility(View.GONE);
                        totalPages = 0;
                        tvItems.setText(Html.fromHtml(getString(R.string.withdraw_records, getResources().getColor(R.color.light_blue), bean.getItems())));
                        return;
                    }
                    updateviewdata(bean);
                    break;
                default:
                    break;
            }


        }
    };

    //更新view绑定数据
    private void updateviewdata(QueryWithdrawRecordBean bean) {
        tvItems.setText(Html.fromHtml(getString(R.string.withdraw_records, getResources().getColor(R.color.light_blue), bean.getItems())));
        tvRwdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_apply_total, getResources().getColor(R.color.light_blue), CommonUtils.formatMoney(CommonUtils.objectToDouble(bean.getApplyAmounts()) / 100))));
        tvWdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_quota_total, getResources().getColor(R.color.light_blue), CommonUtils.formatMoney(CommonUtils.objectToDouble(bean.getAmounts()) / 100))));
        bills = bean.getList();
        queryWithDrawRecordsAdapter.setWithDrawBills(bills);
        if (totalPages < 2) {
            this.footerView.setVisibility(View.GONE);
        } else {
            this.footerView.setVisibility(View.VISIBLE);
        }
        tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages + "页");
        queryBillsSuccessHandler.obtainMessage(UPDATE_VIEW_CODE).sendToTarget();
        HPLog.d(HPLog.SSX_TAG, "pageNo=" + pageNo + "totalPages=" + totalPages);
        if (pageNo == 1) {
            btnLast.setEnabled(false);
        } else {
            btnLast.setEnabled(true);
        }
        if (pageNo == totalPages) {
            btnNext.setEnabled(false);
        } else {
            btnNext.setEnabled(true);
        }

    }

    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        /*if (!super.netResponse(action, resp, true)) {
            if ("zztNewQueryRWDRecords.do".equals(action)) {
				byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData); // 获取到返回的数据
				LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
				// 总笔数
				Double items = (Double) luaTable.rawget("items");
				if (items == null) {
					items = 0d;
				}
				tvItems.setText(Html.fromHtml(getString(R.string.withdraw_records, getResources().getColor(R.color.light_blue), items.intValue())));
				// 总页数
				totalPages = (Double) luaTable.rawget("totalPages");
				Double rwdAmount = (Double) luaTable.rawget("applyAmounts");
				Double wdAmount = (Double) luaTable.rawget("amounts");
				tvRwdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_apply_total, getResources().getColor(R.color.light_blue), rwdAmount / 100)));
				tvWdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_quota_total, getResources().getColor(R.color.light_blue), wdAmount / 100)));
				LuaTable list = (LuaTable) luaTable.rawget("list");
				Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
				if (list != null) {
					bills = new ArrayList<WithdrawRecordsBill>();
					queryWithDrawRecordsAdapter = new WithDrawRecordsAdapter(this, bills);
					WithdrawRecordsListView.setAdapter(queryWithDrawRecordsAdapter);
					for (LuaTable billData : dataList) {
						bills.add(CommonUtils.generateWithdrawRecordsBill(billData));
					}
				}
				if (dataList == null || dataList.size() == 0) {
					DialogFactory.showAlertDialog(this, R.string.tip, R.string.no_wd_data);
					queryWithDrawRecordsAdapter = new WithDrawRecordsAdapter(this, new ArrayList<WithdrawRecordsBill>());
					WithdrawRecordsListView.setAdapter(this.queryWithDrawRecordsAdapter);
					if (pageNo < 2) {
						this.footerView.setVisibility(View.GONE);
					}
					return false;
				}
				tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages.intValue() + "页");
				queryBillsSuccessHandler.obtainMessage(UPDATE_VIEW_CODE).sendToTarget();
				this.footerView.setVisibility(View.VISIBLE);
				if (pageNo == 1) {
					btnLast.setEnabled(false);
				} else {
					btnLast.setEnabled(true);
				}
				if (pageNo == totalPages) {
					btnNext.setEnabled(false);
				} else {
					btnNext.setEnabled(true);
				}
			}
		}*/
        return true;
    }


    @Override
    // set yanglun
    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
        mCalendarDialog.dismiss();
        if (this.isDatePickerDialog4StartDate) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.startDate = calendar.getTime();
            this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 * 1000) - 1);
            this.endDateShowTextView.setText(DateUtils.formatDateToString(endDate, "yyyy-MM-dd"));
        }
    }
}
